package com.maple.phoneward.utils;

import java.util.Locale;

import android.content.Context;
import android.content.Intent;

import com.maple.phoneward.activity.R;
import com.maple.phoneward.constants.Constants;
import com.maple.phoneward.service.LocationService;
import com.maple.phoneward.service.LockedService;

/**
 * CmdUtil.java
 * 
 * @author: YaJian Qiu
 * @Time 2013-4-7 上午9:20:20<br>
 *       本类描述: 远程指令工具类
 */
public class CmdUtil {

	private static String TAG = "CmdUtil";
	/**
	 * 防盗密码
	 */
	private static String PHONEWARD_PASSWORD = "";
	/**
	 * 备份数据协议
	 */
	public String CMD_BACKUP_DATA = "beifen#";
	public String CMD_BACKUP_DATA_1 = "bf#";// 缩写
	/**
	 * 销毁数据协议
	 */
	public String CMD_DESTORY_DATA = "xiaohui#";
	public String CMD_DESTORY_DATA_1 = "xh#";
	/**
	 * 播放警音协议
	 */
	public String CMD_PLAY_SOUND = "baojing#";
	public String CMD_PLAY_SOUND_1 = "bj#";
	/**
	 * 锁定手机协议
	 */
	public String CMD_LOCK_PHONE = "suoding#";
	public String CMD_LOCK_PHONE_1 = "sd#";
	/**
	 * 手机定位协议
	 */
	public String CMD_PHONE_LOCATION = "weizhi#";
	public String CMD_PHONE_LOCATION_1 = "wz#";
	/**
	 * 重置防盗密码
	 */
	public String CMD_RESET_PASSWORD = "chongzhimima";
	public String CMD_RESET_PASSWORD_1 = "czmm";

	private String[] cmds = { CMD_BACKUP_DATA, CMD_DESTORY_DATA, CMD_PLAY_SOUND, CMD_LOCK_PHONE, CMD_PHONE_LOCATION, CMD_RESET_PASSWORD, CMD_BACKUP_DATA_1, CMD_DESTORY_DATA_1,
			CMD_PLAY_SOUND_1, CMD_LOCK_PHONE_1, CMD_PHONE_LOCATION_1, CMD_RESET_PASSWORD_1 };

	private String currentCmd = "";// 当前收到的指令
	private String currentPassword = "";// 当前收到的防盗密码

	private Context context;

	public CmdUtil(Context context) {
		this.context = context;
		// 获取防盗密码，拼装远程指令
		PHONEWARD_PASSWORD = AppUtil.getFromSharedPreferences(context, Constants.CONFIG_PHONEWARD_PASSWORD);
		CMD_BACKUP_DATA += PHONEWARD_PASSWORD;
		CMD_DESTORY_DATA += PHONEWARD_PASSWORD;
		CMD_PLAY_SOUND += PHONEWARD_PASSWORD;
		CMD_LOCK_PHONE += PHONEWARD_PASSWORD;
		CMD_PHONE_LOCATION += PHONEWARD_PASSWORD;
		CMD_BACKUP_DATA_1 += PHONEWARD_PASSWORD;
		CMD_DESTORY_DATA_1 += PHONEWARD_PASSWORD;
		CMD_PLAY_SOUND_1 += PHONEWARD_PASSWORD;
		CMD_LOCK_PHONE_1 += PHONEWARD_PASSWORD;
		CMD_PHONE_LOCATION_1 += PHONEWARD_PASSWORD;
	}

	/**
	 * @param body
	 * @return 是否是指令短信
	 */
	public boolean isCmd(String body) {
		for (String cmd : cmds) {
			if (StringUtil.contains(body.toLowerCase(Locale.getDefault()), cmd.toLowerCase(Locale.getDefault()))) {
				currentCmd = cmd;
				String pwd = body.substring(body.indexOf(cmd) + cmd.length(), body.length());// 从指令中截取防盗密码（密文，要进行md5加密后才能和保存的比较）
				if (StringUtil.isNotEmpty(pwd)) {
					currentPassword = Md5Util.md5(pwd);
					currentCmd += currentPassword;
				}
				Logger.d(TAG, "currentCmd=[" + currentCmd + "]   currentPassword=[" + pwd + "]");
				return true;
			}
		}
		return false;
	}

	/**
	 * 执行指令
	 * 
	 * @param sender
	 * @param body
	 * @return 执行是否成功
	 */
	public boolean executeCmd(String sender, String body) {
		sender = getSender(sender);// 发送指令的手机号码
		Logger.d(TAG, "原始信息  sender=" + sender + "  body=" + body);
		AppUtil.deleteSmsByKeyword(context, body);// 删除指令短信
		new ExecuteThread(sender).start();
		return false;
	}

	/**
	 * 获取发送号码，只留下11位
	 * 
	 * @param sender
	 * @return
	 */
	private String getSender(String sender) {
		if (sender.contains("+86")) {
			sender = sender.replace("+86", "");
		}
		if (sender.contains("12520")) {
			sender = sender.replace("12520", "");// 飞信发送的信息有这个前缀
		}
		return StringUtil.trim(sender);
	}

	/**
	 * @author YaJian Qiu
	 * @time 2013-4-14 下午5:14:02<br>
	 *       本类描述：执行指令的线程
	 * 
	 */
	private class ExecuteThread extends Thread {

		private String sender;

		public ExecuteThread(String sender) {
			this.sender = sender;
			Logger.d(TAG, "线程ID=[" + this.getId() + "]");
		}

		@Override
		public void run() {
			// Logger.d(TAG, "CmdUtil.ExecuteThread.run()");
			String feedback1 = AppUtil.getString(context, R.string.feedback_fail_cause_1);// 防盗密码不正确
			String feedback2 = AppUtil.getString(context, R.string.feedback_fail_cause_2);// 不是安全号码发送指令
			String successTemp = AppUtil.getString(context, R.string.feedback_msg_templete_success);
			String failTemp = AppUtil.getString(context, R.string.feedback_msg_templete_fail);
			String feedbackMsg = "";// 指令执行情况反馈
			if (isPasswordCorrect()) {
				Logger.d(TAG, "防盗密码正确");
				if (compareCmd(CMD_BACKUP_DATA) || compareCmd(CMD_BACKUP_DATA_1)) {// 备份数据
					Logger.d(TAG, "执行备份数据指令");
					AppUtil.backupData(context);
					feedbackMsg = String.format(successTemp, AppUtil.getString(context, R.string.cmd_name_bf));
				} else if (compareCmd(CMD_LOCK_PHONE) || compareCmd(CMD_LOCK_PHONE_1)) {// 锁定手机
					Intent service = new Intent(context, LockedService.class);
					context.startService(service);
					feedbackMsg = String.format(successTemp, AppUtil.getString(context, R.string.cmd_name_sd));
				} else if (compareCmd(CMD_PHONE_LOCATION) || compareCmd(CMD_PHONE_LOCATION_1)) {// 手机定位
					Logger.d(TAG, "执行定位手机指令");
					Intent service = new Intent(context, LocationService.class);
					context.startService(service);
					feedbackMsg = String.format(successTemp, AppUtil.getString(context, R.string.cmd_name_dw));
				} else if (compareCmd(CMD_PLAY_SOUND) || compareCmd(CMD_PLAY_SOUND_1)) {// 播放警音
					Logger.d(TAG, "执行播报警音指令");
					AppUtil.playSound(context, R.raw.sound1, false);
					feedbackMsg = String.format(successTemp, AppUtil.getString(context, R.string.cmd_name_bj));
				} else if (compareCmd(CMD_DESTORY_DATA) || compareCmd(CMD_DESTORY_DATA_1)) {// 销毁数据[需要安全号码发送]
					if (isSafetyNumber(sender)) {
						Logger.d(TAG, "执行销毁数据指令");
						// AppUtil.deleteContacts(context);
						// AppUtil.deleteSmsInfo(context);
						// FileUtil.deletePhotoAndVideo();
						feedbackMsg = String.format(successTemp, AppUtil.getString(context, R.string.cmd_name_xh));
					} else {// 不是安全号码发送的指令
						Logger.d(TAG, "不是安全号码发送的销毁数据指令");
						feedbackMsg = String.format(failTemp, AppUtil.getString(context, R.string.cmd_name_xh), feedback2);
					}

				}
			} else {
				// 重置防盗密码
				if (compareCmd(CMD_RESET_PASSWORD) || compareCmd(CMD_RESET_PASSWORD_1)) {// 重置密码[需要安全号码发送]
					if (isSafetyNumber(sender)) {
						// String newPwd = StringUtil.getRandomPassword();
						String newPwd = "123456";
						// 保存新密码
						AppUtil.saveToSharedPreferences(context, Constants.CONFIG_PHONEWARD_PASSWORD, newPwd);
						// 发送新密给安全号码
						AppUtil.sendMessage(sender, String.format(AppUtil.getString(context, R.string.reset_phoneward_pwd), newPwd));
						feedbackMsg = String.format(successTemp, AppUtil.getString(context, R.string.cmd_name_czmm));
					} else {// 不是安全号码发送的指令
						feedbackMsg = String.format(failTemp, AppUtil.getString(context, R.string.cmd_name_czmm), feedback2);
					}
				} else {// 防盗密码不正确
					Logger.d(TAG, "防盗密码不正确");
					feedbackMsg = String.format(failTemp, "", feedback1);
				}
			}
			AppUtil.sendMessage(sender, feedbackMsg);// 发送反馈信息
		}

		/**
		 * 比较指令
		 * 
		 * @param cmd
		 * @return 是否当前指令
		 */
		private boolean compareCmd(String cmd) {
			String temp1 = currentCmd.toLowerCase(Locale.getDefault());
			String temp2 = cmd.toLowerCase(Locale.getDefault());
			// Logger.d(TAG, "指令比较：temp1="+temp1 + "  temp2="+temp2);
			return StringUtil.equals(temp1, temp2);// 转为小写再比较，即忽略大小写
		}

		/**
		 * @param context
		 * @return 防盗密码是否正确
		 */
		private boolean isPasswordCorrect() {
			return StringUtil.equals(currentPassword, AppUtil.getFromSharedPreferences(context, Constants.CONFIG_PHONEWARD_PASSWORD));
		}

		/**
		 * 是否是安全号码
		 * 
		 * @param sender
		 * @return
		 */
		private boolean isSafetyNumber(String sender) {
			return StringUtil.equals(sender, AppUtil.getFromSharedPreferences(context, Constants.CONFIG_SAFETY_PHONE_NUMBER_1))
					|| StringUtil.equals(sender, AppUtil.getFromSharedPreferences(context, Constants.CONFIG_SAFETY_PHONE_NUMBER_2));
		}
	}

}
